<template>
    <div class="container_form">
        <n-collapse class="header_collapse" display-directive="show">
            <template #header-extra>
                <div class="btn_container">
                    <n-button text size="small" @click="routerBack">
                        {{ $t('button.returnBack') }}
                    </n-button>
                </div>
            </template>
            <n-collapse-item :title="$t('text.teamInfoText')" name="1">
                <TeamInfo />
            </n-collapse-item>
        </n-collapse>
        <section v-show="!isGaming" class="add_btn--wrap">
            <n-button strong secondary @click="startGame" :disabled="isLoadingSession" :loading="isLoadingSession">
                {{ $t('button.createGame') }}
            </n-button>
        </section>
        <GameScheduleProcessing v-if="isGaming" :session @updateSession="updateTotalSession" />
    </div>
</template>

<script setup lang='ts' name="GameForm">
import { useRouter } from 'vue-router';
import TeamInfo from './TeamInfo.vue';
import GameScheduleProcessing from './GameScheduleProcessing.vue';
import storeHelper from '@/utils/TauriStore';
import { getTabProcess } from '@/views/createGame/generator.ts'
import { useMessage } from 'naive-ui';

const session = ref('');
const tabProcessArray = ref<string[]>([]);
const isLoadingSession = ref(true);
const isGaming = ref(false);
const router = useRouter();
const message = useMessage();
const routerBack = () => {
    router.back();
};
const startGame = async () => {
    const flag = await storeHelper.get('hasGame');
    if (!flag) return message.error('请先创建人员战队表单，更新视图！');
    isGaming.value = true;
};
// 更新session 
const updateTotalSession = async () => {
    const tabProcess = await getTabProcess();
    const tabLength = tabProcess.length;
    const sessionIndex = tabProcess.findIndex(item => item === session.value);
    if (sessionIndex === tabLength - 1) {
        session.value = 'all-over';
    }else{
        session.value = tabProcess[sessionIndex + 1] ?? 'all-over';
    }
    storeHelper.set('session', session.value);
}
// 初始化
const _init = async () => {
    try {
        const ruleProcess = await getTabProcess();
        tabProcessArray.value = ruleProcess || [];
        session.value = ruleProcess[0] ?? 'bo1'; //从配置中获取 bo环节
        if (ruleProcess.length === 0) throw new Error('当前规则没用设定任何场次，请先配置赛制规则！');
        isLoadingSession.value = false;
    } catch (error) {
        message.error('获取赛制失败，请检查规则配置！');
        isLoadingSession.value = false;
    }
}
onMounted(() => {
    _init();
})
</script>
<style scoped lang='scss'>
.container_form {
    .header_collapse {
        border-bottom: 1px solid #E7E7E7;

        .btn_container {
            width: 50px;
            text-align: center;
        }
    }

    .add_btn--wrap {
        padding: 24px 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>